package nz.ac.massey.jbuif.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;


/**
 * Class Serialized Data Store Adapter implements  IDataStoreAdapter interface
 * @author AMIR H KIOUMARS
 *
 */
public class SerializedDataStoreAdapter implements IDataStoreAdapter {

	
	/**
	 * Implementing the load the object method
	 * @param file file name
	 * @return a collection of bean objects 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Object> loadObjects(File file) {
		// read in the objects from the file, and put them into a collection.

		Collection<Object> objectsFromFile = null;

		try {
			// System.out.println("Creating Object input stream...");

			FileInputStream fileIn = new FileInputStream(file);
			ObjectInputStream in = new ObjectInputStream(fileIn);

			// System.out.println("Loading Collection...");
			objectsFromFile = (Collection<Object>) in.readObject();

			// System.out.println("Closing input streams.\n");

			in.close();
			fileIn.close();

		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		return objectsFromFile;
	} 

	
	/**
	 * Implementing the save the object method
	 * @param file file name
	 * @param objCollection a collection of bean objects to save
	 */
	@Override
	public void saveObjects(File file, Collection<Object> objCollection) {
		FileOutputStream fOut;
		ObjectOutputStream objOut;

		try {
			fOut = new FileOutputStream(file);
			objOut = new ObjectOutputStream(fOut);
			objOut.writeObject(objCollection);
			
			fOut.close();
			objOut.close();
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
